package crud

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

var templIndex = `<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>列表页面</title>
</head>
<body class="laytp-container">
<div id="search-form" style="display:none;">
    <div class="layui-layer-title">搜索</div>
    <form class="layui-form search-form-body" lay-filter="layui-form" style="margin-top:20px;">
        {{.__SEARCH_LIST__}}

        <div class="layui-form-item layui-inline">
            <label class="layui-form-label" title="名称">名称</label>
            <div class="layui-input-inline">
                <input autocomplete="off" type="text" id="name" name="search_param[name][value]" placeholder="请输入名称" class="layui-input">
                <input type="hidden" name="search_param[name][condition]" value="LIKE">
            </div>
        </div>
		
		<div class="layui-form-item layui-inline">
            <label class="layui-form-label" title="状态">状态</label>
            <div class="layui-input-inline">
                <select id="status" name="search_param[status][value]">
                    <option value="">请选择状态</option>
					<option value="1">显示</option>
                    <option value="2">隐藏</option>
                </select>
                <input type="hidden" name="search_param[status][condition]" value="=">
            </div>
        </div>

        <div class="layui-form-item layui-inline">
            <label class="layui-form-label" title="创建时间">创建时间</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input laydate" id="create_time" name="search_param[create_time][value]"
                       data-type="datetime"
                       data-isRange="true"
                       placeholder="请选择创建时间">
                <input type="hidden" name="search_param[create_time][condition]" value="BETWEEN">
            </div>
        </div>

        <div class="bottom">
            <div class="button-container">
                <button class="laytp-btn laytp-btn-primary laytp-btn-sm" lay-submit="" lay-filter="laytp-search-form">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交
                </button>
                <button type="button" class="laytp-btn laytp-btn-sm laytp-search-form-reset">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
            </div>
        </div>
    </form>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="laytp-table" lay-filter="laytp-table"></table>
    </div>
</div>

<script type="text/html" id="default-toolbar">
    {{.__START__}} if(facade.hasAuth("{{.__API_PREFIX__}}add") {{.__ONLY__}} ){ {{.__END__}}
    <button class="laytp-btn laytp-btn-danger laytp-btn-md" lay-event="add">
        <i class="layui-icon layui-icon-add-1"></i>
        新增
    </button>
    {{.__START__}} } {{.__END__}}
    <button class="laytp-btn laytp-btn-warming laytp-btn-md" lay-event="search">
        <i class="layui-icon layui-icon-search"></i>
        搜索
    </button>
</script>

<script type="text/html" id="default-bar">
    {{.__START__}} if(facade.hasAuth("{{.__API_PREFIX__}}edit") {{.__ONLY__}} ){ {{.__END__}}
    <button class="laytp-btn laytp-btn-primary laytp-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</button>
    {{.__START__}} } {{.__END__}}
    {{.__START__}} if(facade.hasAuth("{{.__API_PREFIX__}}del")){ {{.__END__}}
    <button class="laytp-btn laytp-btn-danger laytp-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</button>
    {{.__START__}} } {{.__END__}}
</script>

<script>
    if(localStorage.getItem("staticDomain")){
        document.write("<link rel='stylesheet' href='" + localStorage.getItem("staticDomain") + "/component/laytp/css/laytp.css?v=" + localStorage.getItem("version") + "'>");
        document.write("<script src='" + localStorage.getItem("staticDomain") + "/component/layui/layui.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='" + localStorage.getItem("staticDomain") + "/component/laytp/layuiConfig.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='/static/component/jquery_3.3.1.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='/static/component/jquery.tablednd.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='{{.__JSPATH__}}'><\/script>");
    }else{
        document.write("<link rel='stylesheet' href='/static/component/laytp/css/laytp.css?v=" + localStorage.getItem("version") + "'>");
        document.write("<script src='/static/component/layui/layui.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='/static/component/laytp/layuiConfig.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='/static/component/jquery_3.3.1.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='/static/component/jquery.tablednd.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='{{.__JSPATH__}}'><\/script>");
    }

</script>
</body>
</html>`
var tempAdd = `<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>添加页面</title>
</head>
<body>
<form class="layui-form" lay-filter="layui-form">
  <div class="mainBox">
    <div class="main-container">
        {{.__FIELD__}}
    </div>
  </div>
  <div class="bottom">
    <div class="button-container">
      <button type="submit" class="laytp-btn laytp-btn-primary laytp-btn-sm" lay-submit="" lay-filter="add">
        <i class="layui-icon layui-icon-ok"></i>
        提交
      </button>
      <button type="reset" class="laytp-btn laytp-btn-sm">
        <i class="layui-icon layui-icon-refresh"></i>
        重置
      </button>
    </div>
  </div>
</form>
<script>
  if(localStorage.getItem("staticDomain")){
    document.write("<link rel='stylesheet' href='" + localStorage.getItem("staticDomain") + "/component/laytp/css/laytp.css?v=" + localStorage.getItem("version") + "'>");
    document.write("<script src='" + localStorage.getItem("staticDomain") + "/component/layui/layui.js?v="+localStorage.getItem("version")+"'><\/script>");
    document.write("<script src='" + localStorage.getItem("staticDomain") + "/component/laytp/layuiConfig.js?v="+localStorage.getItem("version")+"'><\/script>");
  }else{
    document.write("<link rel='stylesheet' href='/static/component/laytp/css/laytp.css?v=" + localStorage.getItem("version") + "'>");
    document.write("<script src='/static/component/layui/layui.js?v="+localStorage.getItem("version")+"'><\/script>");
    document.write("<script src='/static/component/laytp/layuiConfig.js?v="+localStorage.getItem("version")+"'><\/script>");
  }
</script>
<script>
  layui.use(['laytp'],function(){
    layui.form.on('submit(add)', function(data){
      var btnAnim = layui.button.load({elem:$(this)});
      try{
        data = facade.setEditorField(data);
      }catch (e) {
        facade.error(e);
        return false;
      }
      facade.ajax({
        route:'{{.__API_PREFIX__}}{{.__ACT__}}',
        data : data.field
      }).done(function(res){
        if(res.code === 0){
          parent.layui.layer.close(parent.layui.layer.getFrameIndex(window.name));//关闭当前页
          parent.layui.table.reloadData("laytp-table");
        }
        btnAnim.stop();
      }).fail(function(){
        btnAnim.stop();
      });
      return false;
    });
  })
</script>
</body>
</html>`
var tempEdit = `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>编辑页面</title>
</head>
<body>
<script type="text/html" id="form">
    <input type="hidden" name="id" value="{{.__ID__}}" />
    <div class="mainBox">
        <div class="main-container">
			{{.__FIELD__}}
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="laytp-btn laytp-btn-primary laytp-btn-sm" lay-submit="" lay-filter="laytp-form">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="laytp-btn laytp-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</script>
<form class="layui-form" lay-filter="layui-form"></form>
<script>
    if(localStorage.getItem("staticDomain")){
        document.write("<link rel='stylesheet' href='" + localStorage.getItem("staticDomain") + "/component/laytp/css/laytp.css?v=" + localStorage.getItem("version") + "'>");
        document.write("<script src='" + localStorage.getItem("staticDomain") + "/component/layui/layui.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='" + localStorage.getItem("staticDomain") + "/component/laytp/layuiConfig.js?v="+localStorage.getItem("version")+"'><\/script>");
    }else{
        document.write("<link rel='stylesheet' href='/static/component/laytp/css/laytp.css?v=" + localStorage.getItem("version") + "'>");
        document.write("<script src='/static/component/layui/layui.js?v="+localStorage.getItem("version")+"'><\/script>");
        document.write("<script src='/static/component/laytp/layuiConfig.js?v="+localStorage.getItem("version")+"'><\/script>");
    }
</script>
<script>
    layui.use(['laytp'],function(){
        let form = layui.form;
        let $ = layui.jquery;
        //获取参数ID
        var id = facade.getUrlParam('id');
        if(!id){
            facade.error('参数ID不能为空');
            return false;
        }

        //获取数据，渲染到对应的节点上
        facade.ajax({
            route: "{{.__API_PREFIX__}}info",
            data: {id: id},
            successAlert: false,
            showLoading: true
        }).done(function(res){
            if(res.code === 0){
                layui.laytpl($("#form").html()).render(res.data,function(string){
                    $("form").html(string);
                    layui.laytpForm.render();
                    form.render();
                });
            }
        });

        form.on('submit(laytp-form)', function(data){
            var btnAnim = layui.button.load({elem:$(this)});
            try{
                data = facade.setEditorField(data);
            }catch (e) {
                facade.error(e);
                return false;
            }
            facade.ajax({
                route:'{{.__API_PREFIX__}}{{.__ACT__}}',
                data:data.field
            }).done(function(res){
                if(res.code === 0){
                    parent.layui.layer.close(parent.layui.layer.getFrameIndex(window.name));//关闭当前页
                    parent.layui.table.reloadData("laytp-table");
                }
                btnAnim.stop();
            }).fail(function(){
                btnAnim.stop();
            });
            return false;
        });
    })
</script>
</body>
</html>`

func (g *cGlobal) getListHtml() string {
	__SEARCH_LIST__ := ""
	if g.Field != nil {
		if _, ok := g.Field["user_id"]; ok {
			__SEARCH_LIST__ += `
			<div class="layui-form-item layui-inline">
            <label class="layui-form-label" title="会员列表">会员列表</label>
            <div class="layui-input-inline">
                <div class="xmSelect"
                     data-name="search_param[user_id][value]"
                     data-sourceType="route"
					 data-textField="realname"
                     data-radio="true"
                     data-source='/admin.member/index'
                     data-selected=""
                ></div>
                <input type="hidden" name="search_param[user_id][condition]" value="=">
            </div>
        </div>`
		}

		if _, ok := g.Field["level_id"]; ok {
			__SEARCH_LIST__ += `
			<div class="layui-form-item layui-inline">
            <label class="layui-form-label" title="年级列表">年级列表</label>
            <div class="layui-input-inline">
                <div class="xmSelect"
                     data-name="search_param[level_id][value]"
                     data-sourceType="route"
                     data-radio="true"
                     data-source='/admin.custom.level/index'
                     data-selected=""
                ></div>
                <input type="hidden" name="search_param[level_id][condition]" value="=">
            </div>
        </div>`
		}

		if _, ok := g.Field["article_id"]; ok {
			__SEARCH_LIST__ += `
			<div class="layui-form-item layui-inline">
            <label class="layui-form-label" title="文章列表">文章列表</label>
            <div class="layui-input-inline">
                <div class="xmSelect"
                     data-name="search_param[article_id][value]"
                     data-sourceType="route"
                     data-radio="true"
                     data-source='/admin.custom.article/index'
                     data-selected=""
                ></div>
                <input type="hidden" name="search_param[article_id][condition]" value="=">
            </div>
        </div>`
		}

		if _, ok := g.Field["rule_id"]; ok {
			__SEARCH_LIST__ += `
			<div class="layui-form-item layui-inline">
            <label class="layui-form-label" title="答案列表">答案列表</label>
            <div class="layui-input-inline">
                <div class="xmSelect"
                     data-name="search_param[rule_id][value]"
                     data-sourceType="route"
                     data-radio="true"
                     data-source='/admin.custom.article.rule/index'
                     data-selected=""
                ></div>
                <input type="hidden" name="search_param[rule_id][condition]" value="=">
            </div>
        </div>`
		}

		if _, ok := g.Field["order_id"]; ok {
			__SEARCH_LIST__ += `
			<div class="layui-form-item layui-inline">
            <label class="layui-form-label" title="订单列表">订单列表</label>
            <div class="layui-input-inline">
                <div class="xmSelect"
                     data-name="search_param[order_id][value]"
                     data-sourceType="route"
                     data-radio="true"
                     data-source='/admin.order/index'
                     data-selected=""
                ></div>
                <input type="hidden" name="search_param[order_id][condition]" value="=">
            </div>
        </div>`
		}

		if _, ok := g.Field["shop_id"]; ok {
			__SEARCH_LIST__ += `
			<div class="layui-form-item layui-inline">
            <label class="layui-form-label" title="订单列表">订单列表</label>
            <div class="layui-input-inline">
                <div class="xmSelect"
                     data-name="search_param[shop_id][value]"
                     data-sourceType="route"
                     data-radio="true"
                     data-source='/admin.shop/index'
                     data-selected=""
                ></div>
                <input type="hidden" name="search_param[shop_id][condition]" value="=">
            </div>
        </div>`
		}
	}

	return __SEARCH_LIST__
}

func (g *cGlobal) doIndex() error {
	err := os.MkdirAll(g.AppPath.HtmlPath, os.ModePerm)
	if err != nil {
		return err
	}

	jsPrefix := g.JsURI
	__SEARCH_LIST__ := g.getListHtml()
	__ONLY__ := ""
	if g.OnlyIndex {
		__ONLY__ = " && false"
	}

	m := map[string]string{
		"__API_PREFIX__":  jsPrefix,
		"__JSPATH__":      g.JsURLPath,
		"__SEARCH_LIST__": __SEARCH_LIST__,
		"__START__":       "{{#",
		"__END__":         "}}",
		"__ONLY__":        __ONLY__,
	}

	fileName := g.AppFiles.HtmlIndex
	err = TemplateExec(fileName, templIndex, m)
	if err != nil {
		return err
	}

	return nil
}

func (g *cGlobal) doHtml(s string, tmpl string) error {
	err := os.MkdirAll(g.AppPath.HtmlPath, os.ModePerm)
	if err != nil {
		return err
	}

	tbInfo := g.TableSchema
	fields := make([]string, 0)

	if g.Field != nil {
		for key, val := range g.Field {
			if key == "id" || key == "create_time" || key == "update_time" || key == "delete_time" {
				continue
			}

			label := val["name"]
			txtVal := ""
			sVal := ""
			if key == "status" {
				if s == "edit" {
					txtVal = `{{# if(1 == d.status){ }}checked="checked"{{# } }}`
				} else {
					txtVal = `checked`
				}
				sVal = fmt.Sprintf(`<div class="layui-form-item">
                    <label class="layui-form-label" title="%v">%v</label>
                    <div class="layui-input-block">
                        <input type="hidden" name="%v" id="%v-2" value="2" />
                        <input type="checkbox" name="%v" id="%v-1" lay-skin="switch" lay-text="正常|隐藏" value="1" %v />
                    </div>
                </div>`, label, label, key, key, key, key, txtVal)
			} else if key == "user_id" {
				sVal = fmt.Sprintf(`<div class="layui-form-item">
                    <label class="layui-form-label" title="%v">%v</label>
                    <div class="layui-input-block">
                        <div class="xmSelect"
		                     data-name="user_id"
		                     data-sourceType="route"
							 data-textField="realname"
		                     data-radio="true"
		                     data-source='/admin.member/index'
		                     data-selected="{{=d.user_id}}"
		                ></div>
                    </div>
                </div>`, label, label)
			} else if key == "level_id" {
				sVal = fmt.Sprintf(`<div class="layui-form-item">
                    <label class="layui-form-label" title="%v">%v</label>
                    <div class="layui-input-block">
                        <div class="xmSelect"
		                     data-name="level_id"
		                     data-sourceType="route"
		                     data-radio="true"
		                     data-source='/admin.custom.level/index'
		                     data-selected="{{=d.level_id}}"
		                ></div>
                    </div>
                </div>`, label, label)
			} else if key == "order_id" {
				sVal = fmt.Sprintf(`<div class="layui-form-item">
                    <label class="layui-form-label" title="%v">%v</label>
                    <div class="layui-input-block">
                        <div class="xmSelect"
		                     data-name="order_id"
		                     data-sourceType="route"
		                     data-radio="true"
		                     data-source='/admin.member.order/index'
		                     data-selected="{{=d.order_id}}"
		                ></div>
                    </div>
                </div>`, label, label)
			} else {
				if s == "edit" {
					txtVal = fmt.Sprintf("{{=d.%v}}", key)
				} else {
					if key == "sort" {
						txtVal = "0"
					}
				}
				sVal = fmt.Sprintf(`<div class="layui-form-item">
    				<label class="layui-form-label" title="%v">%v</label>
    				<div class="layui-input-block">
            			<input autocomplete="off" type="text" name="%v" id="%v" placeholder="请输入%v" class="layui-input" value="%v">
    				</div>
				</div>`, label, label, key, key, label, txtVal)
			}

			fields = append(fields, sVal)
		}
	} else {
		for _, column := range tbInfo {
			if column["column"] == "id" || column["ctype"] == "datetime" || column["ctype"] == "create_time" || column["ctype"] == "update_time" || column["ctype"] == "delete_time" {
				continue
			}

			comment := column["comment"]
			label := comment
			sVal := ""
			txtVal := ""
			if comment != "" {
				if idx := strings.Index(comment, "("); idx > 0 {
					label = comment[:idx]

					rules := comment[idx+1:]
					rules = strings.ReplaceAll(rules, "(", "")
					rules = strings.ReplaceAll(rules, ")", "")

					if strings.Index(comment, "radio") > 0 {
						rules = strings.ReplaceAll(rules, "radio:", "")
						var tmp []map[string]string
						err = json.Unmarshal([]byte(rules), &tmp)
						if err != nil {
							continue
						}

						switchVal := ""

						for _, sv := range tmp {
							check := ""
							if sv["id"] == "1" {
								check = fmt.Sprintf(`{{#if (d.sex == '%v'){ }}checked="checked"{{# } }}`, sv["id"])
							}

							switchVal += fmt.Sprintf(`<input type="radio" name="%v" id="%v-%v" value="%v" title="%v" %v />`, column["column"], column["column"], sv["id"], sv["id"], sv["name"], check)
							switchVal += "\n"
						}

						sVal = fmt.Sprintf(`<div class="layui-form-item">
    				<label class="layui-form-label" title="%v">%v</label>
    				<div class="layui-input-block">
            			%v
    				</div>
				</div>`, label, label, switchVal)
					} else {
						if s == "edit" {
							txtVal = fmt.Sprintf("{{=d.%v}}", column["column"])
						}
						sVal = fmt.Sprintf(`<div class="layui-form-item">
    				<label class="layui-form-label" title="%v">%v</label>
    				<div class="layui-input-block">
            			<input autocomplete="off" type="text" name="%v" id="%v" placeholder="请输入%v" class="layui-input" value="%v">
    				</div>
				</div>`, label, label, column["column"], column["column"], label, txtVal)
					}
				}
			} else {
				label = column["column"]

				if s == "edit" {
					txtVal = fmt.Sprintf("{{=d.%v}}", column["column"])
				} else {
					if column["column"] == "sort" {
						txtVal = "0"
					}
				}
				sVal = fmt.Sprintf(`<div class="layui-form-item">
    				<label class="layui-form-label" title="%v">%v</label>
    				<div class="layui-input-block">
            			<input autocomplete="off" type="text" name="%v" id="%v" placeholder="请输入%v" class="layui-input" value="%v">
    				</div>
				</div>`, label, label, column["column"], column["column"], label, txtVal)
			}

			fields = append(fields, sVal)
		}
	}

	idStr := ""
	if s == "edit" {
		idStr = `{{= d.id }}`
	}

	jsPrefix := g.JsURI

	m := map[string]string{
		"__API_PREFIX__": jsPrefix,
		"__ACT__":        s,
		"__ID__":         idStr,
		"__FIELD__":      strings.Join(fields, ""),
	}

	fileName := ""
	if s == "add" {
		fileName = g.AppFiles.HtmlAdd
	} else {
		fileName = g.AppFiles.HtmlEdit
	}

	err = TemplateExec(fileName, tmpl, m)
	if err != nil {
		return err
	}

	return nil
}

func (g *cGlobal) MakeHtml() error {
	err := g.doIndex()
	if err != nil {
		return err
	}

	if g.OnlyIndex {
		return nil
	}

	err = g.doHtml("add", tempAdd)
	if err != nil {
		return err
	}

	err = g.doHtml("edit", tempEdit)
	if err != nil {
		return err
	}

	return nil
}
